/**
 * 工具类
 */
/*
 * @description: 公用方法文件
 * 使用方式: this.$util.方法名
 */
const util = {
	/**
	 * 时间戳格式化
	 * @param {Number} datetime 时间戳(秒)
	 * @param {String} formateType 时间戳所需处理的方式 normal(月日时分),info(年月日时分秒),rule(年月日时分秒,date(年月日)
	 * @param {String} joinType 日期间隔符号
	 * @return {String}  日期字符串
	 */
	formatTime(datetime, formateType, joinType) {
		const date = new Date(Number(datetime) * 1000),
			year = date.getFullYear(),
			month = date.getMonth() + 1,
			day = date.getDate(),
			hour = date.getHours(),
			minute = date.getMinutes(),
			second = date.getSeconds(),
			formatNumber = function formatNumber(n) {
				n = n.toString();
				return n[1] ? n : '0' + n;
			},
			timeType = {
				'normal': [
					[month, day],
					[hour, minute]
				],
				'info': [
					[year, month, day],
					[hour, minute, second]
				],
				'rule': [
					[year, month, day],
					[hour, minute]
				],
			};
		if (formateType == 'date') {
			return [year, month, day].map(formatNumber).join(joinType);
		} else {
			return timeType[formateType][0].map(formatNumber).join(joinType) + ' ' + timeType[formateType][1].map(formatNumber)
				.join(':');
		}
	},

	/**
	 * 计算距离时间
	 * @param {String} dateStr 时间格式字符串 yyyy-mm-dd HH:MM:ss
	 * @return {String}  日期字符串
	 */
	dateDistance(dateStr) {
		let UNITS = {
				'年': 31557600000,
				'月': 2629800000,
				'天': 86400000,
				'小时': 3600000,
				'分钟': 60000,
				'秒': 1000
			},
			humanize = function(milliseconds) {
				var humanize = '';
				for (var key in UNITS) {
					if (milliseconds >= UNITS[key]) {
						humanize = Math.floor(milliseconds / UNITS[key]) + key + '前';
						break;
					}
				}
				return humanize || '刚刚';
			},
			format = function(dateStr) {
				var date = parse(dateStr)
				var diff = Date.now() - date.getTime();
				if (diff < UNITS['天']) {
					return humanize(diff);
				}
				var _format = function(number) {
					return (number < 10 ? ('0' + number) : number);
				};
				return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
					_format(date.getHours()) + ':' + _format(date.getMinutes());
			},
			parse = function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
				var a = str.split(/[^0-9]/);
				return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
			};
		return format(dateStr);
	},

	/**
	 * Base64编码解码
	 * @return {String}  Base64字符串
	 * 使用方法：new Base64().encode(String) , new Base64().decode(String)
	 */
	Base64() {
		var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

		// 编码
		this.encode = function(input) {
			var output = "";
			var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
			var i = 0;
			input = _utf8_encode(input);
			while (i < input.length) {
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
				output = output +
					_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
					_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
			}
			return output;
		}

		// 解码
		this.decode = function(input) {
			var output = "";
			var chr1, chr2, chr3;
			var enc1, enc2, enc3, enc4;
			var i = 0;
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
			while (i < input.length) {
				enc1 = _keyStr.indexOf(input.charAt(i++));
				enc2 = _keyStr.indexOf(input.charAt(i++));
				enc3 = _keyStr.indexOf(input.charAt(i++));
				enc4 = _keyStr.indexOf(input.charAt(i++));
				chr1 = (enc1 << 2) | (enc2 >> 4);
				chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				chr3 = ((enc3 & 3) << 6) | enc4;
				output = output + String.fromCharCode(chr1);
				if (enc3 != 64) {
					output = output + String.fromCharCode(chr2);
				}
				if (enc4 != 64) {
					output = output + String.fromCharCode(chr3);
				}
			}
			output = _utf8_decode(output);
			return output;
		}

		let _utf8_encode = function(string) {
			string = string.replace(/\r\n/g, "\n");
			var utftext = "";
			for (var n = 0; n < string.length; n++) {
				var c = string.charCodeAt(n);
				if (c < 128) {
					utftext += String.fromCharCode(c);
				} else if ((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				} else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}

			}
			return utftext;
		}

		let _utf8_decode = function(utftext) {
			var string = "";
			var i = 0;
			var c2 = 0,
				c1 = c2,
				c = c1;
			while (i < utftext.length) {
				c = utftext.charCodeAt(i);
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				} else if ((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i + 1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				} else {
					c2 = utftext.charCodeAt(i + 1);
					var c3 = utftext.charCodeAt(i + 2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
			}
			return string;
		}
	},

	/**
	 * 获取对象里每一项的值(代替Object.values())
	 * @param {Object} obj 一个对象
	 * @return {String}  一个给定对象自身的所有属性值的数组
	 */
	objectValues(obj) {
		let valuesArray = []
		if (obj) {
			for (let key in obj) {
				valuesArray.push(obj[key]);
			}
		}
		return valuesArray
	},

	/**
	 * 请求转换成Promise对象
	 * @param {Object} options 请求参数
	 * @param {Object} pageObj 当前页面实例
	 * @param {Boolean} isToken 请求是否需要携带用户token
	 * @returns {Promise} Promise对象
	 */
	requestPromise(options, pageObj, isToken = false) {
		return new Promise((resolve, reject) => {
			pageObj.$request({ ...options
			}, res => resolve(res), pageObj, isToken);
		});
	},

	/**
	 * scene解码
	 */
	scene_decode(e) {
		if (e === undefined)
			return {};
		let scene = decodeURIComponent(e),
			params = scene.split(','),
			data = {};
		for (let i in params) {
			var val = params[i].split(':');
			val.length > 0 && val[0] && (data[val[0]] = val[1] || null)
		}
		return data;
	},

	/**
	 * 防止滚动触发多次函数
	 * @param {Number} wait 重复间隔
	 * @param {Function} handler 处理操作
	 */
	scorllTimert: null,
	debounce(wait, handler) {
		let that = this;
		return (() => {
			// 每次触发 scroll 时先清除定时器
			clearTimeout(that.scorllTimert);
			that.scorllTimert = setTimeout(() => {
				handler();
			}, wait);
		})();
	},

	/**
	 * 获取url链接参数
	 * @param {String} name 需要获取的参数名
	 * @param {String} params url链接
	 * @param {Boolean} ishref 是否使用完整的href路径作为正则匹配的参数 默认为否
	 */
	getParams(name, params, ishref = !1) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = !!params ? (ishref ? params.includes('?') && params.split('?')[1].match(reg) : params.match(reg)) : null;
		if (Object.prototype.toString.call(r) == "[object Array]") {
			return r[2];
		}
		if (r != null) {
			return unescape(r[2]);
		}
		return r || null;
	},

	/**
	 * 坐标系转换
	 */
	// bd09转gcj02
	baidu_To_qq(lat, lon) {
		let x_pi = 3.14159265358979324 * 3000.0 / 180.0,
			x = lon - 0.0065,
			y = lat - 0.006,
			z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi),
			theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi),
			latitude = z * Math.cos(theta),
			longitude = z * Math.sin(theta),
			gps = {
				latitude,
				longitude
			};
		return gps;
	},
	//gcj02转bd09
	qq_To_baidu(lat, lng) {
		let x_PI = 3.14159265358979324 * 3000.0 / 180.0,
			z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI),
			theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI),
			latitude = z * Math.cos(theta) + 0.0065,
			longitude = z * Math.sin(theta) + 0.006,
			gps = {
				latitude,
				longitude
			};
		return gps;
	},
	
	// 浮点数计算
	// @digit {Number} 浮点数乘以的次方
	// 加法 
	additionFloat(one,two,digit){
		let num=((one*digit)+(two*digit))/digit
		return num;
	},
	// 减法
	subtractionFloat(one,two,digit){
		let num=((one*digit)-(two*digit))/digit
		return num;
	},
	// 乘法
	multiplicationFloat(one,two,digit){
		let num=((one*digit)*(two*digit))/(digit*digit)
		return num;
	},
	// 除法
	divisionFloat(one,two,digit){
		let num=((one*digit)/(two*digit))/(digit*digit)
		return num;
	},
	
};
export default util
